/*
 * author: Kai Jiang
 * Date: Feb 27 2014
 * CS202
 * Assignment 3
 * purpose: complete member functions in class paragraph.h
 */

#include <iostream>
#include <cstdio>
#include <cstring>
#include "paragraph.h"
using namespace std;

/* class paragraph
 * member functions
 *
 *
 */
 
//constructor
paragraph::paragraph(){
	cntSentence = 0;
	head = NULL;
	tail = NULL;
}

paragraph::~paragraph(){
	nodeSentence * cur;
	while (head){
		cur = head -> next;
		delete head;
		head = cur;
	}
}

//copy
paragraph& paragraph::operator = (const paragraph& l){
	if ( this == &l )
		return *this;
	nodeSentence* cur;

	//If there is a paragraph, delete its words
	while( head ){
		cur = head -> next;
		delete head;
		head = cur;
	}

	if (!l.head)
		head = tail = ptr = NULL;
	else{
		head = new nodeSentence;
		head -> data = l.head -> data;

		nodeSentence* dest = head;
		nodeSentence* source = l.head -> next;
		while (source){
			dest -> next = new nodeSentence;
			dest = dest -> next;
			dest -> data = source -> data;
			source = source -> next;
		}
		dest -> next = NULL;
		tail = dest;
		ptr = head;
	}
	return *this;
}

//output
ostream& operator << (ostream& out, const paragraph& l){
	nodeSentence* cur = l.head;
	while (cur){
		out << cur -> data;
		cur = cur -> next;
	}
	out << endl << endl;
	return out;
}

//compare
bool paragraph::operator == (const paragraph& s) const{
	nodeSentence* first = head;
	nodeSentence* second = s.head;
	while(first && second && first -> data == second -> data){
		first = first -> next;
		second = second -> next;
	}
	if (first || second)
		return false;
	else
		return true;
}

//compare
bool paragraph::operator != (const paragraph& s) const{
	return !(*this == s);
}

paragraph& paragraph::operator = (const sentence& s){
	// if ( this -> head -> next == NULL && this -> head -> data == s ){
	// 	return *this;
	// }
	nodeSentence* cur;

	//If there is a paragraph, delete its sentences
	while( head ){
		cur = head -> next;
		delete head;
		head = cur;
	}
	if ( !s.length() ){
		head = tail = ptr = NULL;
		cntSentence = 0;
	}
	else{
		head = new nodeSentence;
		head -> data = s;
		head -> next = NULL;
		tail = head;
	}	
	return *this;
}

//append
paragraph& paragraph::operator += (const sentence& s){
	if (!head)
		*this = s;
	else{
		nodeSentence* dest = this -> tail;
		dest -> next = new nodeSentence;
		this -> cntSentence++;
		dest = dest -> next;
		dest -> data = s;
		dest -> next = NULL;
		this -> tail = dest;
		this -> ptr = this -> head;
	}
}
